# -*- coding: utf-8-*-
# from openerp import models,api
from openerp.osv import osv, fields
from urlparse import urlparse


# 微信企业号应用
class wechat_application(osv.osv):
    _name = 'wechat.application'
    _description = u"微信应用"
    
    _columns = {
        'enterprise_id': fields.many2one('wechat.enterprise', u'企业号', required=True),
        'name': fields.char(u'应用名称'),
        'description': fields.char(u'介绍'),
        'logo': fields.binary('Logo'),
        'application_id': fields.char(u'微信应用ID'),
        'secret': fields.char(u'秘钥'), #新企业微信（针对微信企业号来说），用于获取access_token
        'access_token': fields.char(u'微信接口主动调用token'),  # 7200秒有效期
        'access_token_timestamp': fields.integer(u'token起始时间戳'),
        'jsapi_ticket': fields.char(u'微信jsapi调用ticket'),  # 7200秒有效期
        'jsapi_ticket_timestamp': fields.integer(u'jsapi ticket起始时间戳'),
        'callback_mode': fields.boolean(u'回调模式'),
        'callback_url': fields.char(u'回调URL'),
        'callback_token': fields.char(u'回调Token'),
        'callback_aeskey': fields.char(u'回调EncodingAESKey'),

        'redirect_domain': fields.char('可信域名'),
        'report_location_flag': fields.selection([('none', u'不上报'), ('enter', u'进入回话上报'),\
             ('continue', u'持续上报')], string=u'上报地理位置'),
        'is_report_user': fields.boolean(u'状态变更通知'),
        'is_report_enter': fields.boolean(u'上报进入应用事件'),
        'menu_ids': fields.one2many('wechat.agent.menu', 'agent_id', u'菜单'),
        'permission_group_ids': fields.many2many('wechat.permission.group', 'application_permission_ref', 'application_id', 'permission_id', u'相关权限'),
    }

    _sql_constraints = [
        ('application_id_uniq', 'unique(enterprise_id, application_id)', '用户企业号中的应用号必须唯一')
    ]

    def get_callback_host(self, cr, uid, context=None):
        application_ids = self.search(cr, uid, [], limit=1, context=context)
        if application_ids:
            url = self.read(cr, uid, application_ids[0], ['callback_url'], context=context).get('callback_url')
            if url:
                url = urlparse(url)
                return url.scheme + '://' + url.netloc
            else:
                raise osv.except_osv(u'错误', u'微信应用中没有设定回调URL')
        else:
            raise osv.except_osv(u'错误', u'企业号中没有配置应用信息')

    def get_authenticate_access_token(self, cr, uid, context=None):
        cr.execute("SELECT * FROM auth_oauth_provider WHERE name='weixin'")
        auth_oauth_provider = cr.dictfetchone()
        if not auth_oauth_provider:
            raise Exception('Not found auth_oauth_provider: weixin')

        # 取得有权限的app(获得access_token)
        wechat_permission_app_id = auth_oauth_provider.get('wechat_permission_app_id')
        app = self.pool.get('wechat.application').browse(cr, uid, wechat_permission_app_id, context=context)
        if app and app.access_token:
            return app.access_token

        raise osv.except_osv(u'错误', u'查不到主键为1的微信应用')

    def init(self, cr):
        cr.execute("""
        update ir_model_data set noupdate=false where
         name in ('weixin_dftg_assistant_application',
          'weixin_dftg_test_application',
           'weixin_dftg_test2_application',
            'weixin_dftg_assistant_mshop',
             'weixin_dftg_work_application', 'provider_weixin');
        delete from wechat_application where name='东方团购客服';
        """)
